//
//  HMComposeViewController.swift
//  Weibo
//
//  Created by teacher on 2017/6/11.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit
import SVProgressHUD

//  撰写视图控制器
class HMComposeViewController: UIViewController {

    //  MARK:   --懒加载控件
    private lazy var titleLabel: UILabel = {
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGray)
        if let name = HMUserAccountViewModel.sharedViewModel.userAccount?.name {
            let content = "发微博\n\(name)"
            //  字符串转成富文本
            let attributedStr = NSMutableAttributedString(string: content)
            //  获取名字的范围
            let range = (content as NSString).range(of: name)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.orange], range: range)
            //  设置富文本
            label.attributedText = attributedStr
        } else {
            label.text = "发微博"
        }
        //  多行显示
        label.numberOfLines = 0
        //  文字居中
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    //  发送按钮
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside)
        //  设置不同状态下对应的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    //  textView
    fileprivate lazy var textView: HMComposeTextView = {
        let textView = HMComposeTextView()
        textView.delegate = self
        //  不显示纠错提示
//        textView.autocorrectionType = .no
        textView.placeHolder = "听说下雨天音乐和辣条更配哟~听说下雨天音乐和辣条更配哟~听说下雨天音乐和辣条更配哟~听说下雨天音乐和辣条更配哟~"
        textView.font = UIFont.systemFont(ofSize: 14)
        //  垂直方向拖动
        textView.alwaysBounceVertical = true
        return textView
    }()
    //  toolbar
    fileprivate lazy var toolBar: HMComposeToolBar = HMComposeToolBar()
    
    //  配图
    fileprivate lazy var pictureView: HMComposePictureView = {
        let collectionView = HMComposePictureView()
        collectionView.backgroundColor = self.textView.backgroundColor
        return collectionView
    }()
    
    //  表情键盘
    fileprivate lazy var emoticonKeyBoard: HMEmoticonKeyBoard = {
        let keyBoard = HMEmoticonKeyBoard(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: ScreenWidth, height: 216)))
        return keyBoard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
    }
    
    //  设置导航栏按钮和titleView
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //  右侧导航栏按钮不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
        
    }
    
    private func setupUI() {
        
        //  监听键盘frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //  监听表情按钮点击的通知
        NotificationCenter.default.addObserver(self, selector: #selector(clickEmoticonButtonAction(noti:)), name: NSNotification.Name(ClickEmotionButtonNotificationName), object: nil)
        //  监听删除按钮点击的通知
        NotificationCenter.default.addObserver(self, selector: #selector(clickDeleteButtonAction), name: NSNotification.Name(ClickDeleteButtonNotificationName), object: nil)
        
        setupNavUI()
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(toolBar)
        
        
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        toolBar.snp.makeConstraints { (make) in
            make.bottom.leading.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp.width).offset(-20)
        }
        
        //  设置闭包
        //  使用self会产生循环引用，需要使用[unowned self]
        toolBar.callBack = {[unowned self] (type: HMComposeToolBarButtonType) in
            switch type {
            case .picture:
                print("图片")
                self.pictureButtonAction()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self.emoticonButtonAction()
            case .add:
                print("加号")
            }
        
        }
        //   使用弱引用解决循环引用
        pictureView.addPictureCallBack = { [unowned self] in
            //  打开图片浏览器
            self.pictureButtonAction()
        }
    
    }
    
    //  MARK:   --发送按钮点击事件处理
    @objc private func sendButtonAction() {
        //  令牌
        let token = HMUserAccountViewModel.sharedViewModel.accessToken!
        //  微博内容
//        let text = textView.text!
        //  获取富文本对应的富文本内容
        let text = textView.emoticonText
        
        
        //  发送等待提示
        SVProgressHUD.show()
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            //  发图片
            HMNetworkTools.sharedTools.sendMessage(token: token, status: text, pic: image, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败!")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
            })
        } else {
            //  发送文字
            HMNetworkTools.sharedTools.sendMessage(token: token, status: text) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败!")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
            }
        }
        
    }
    
    //  MARK:   --删除按钮的点击的通知方法
    @objc private func clickDeleteButtonAction() {
        //  回删内容
        textView.deleteBackward()
    }
   
    //  MARK:   --表情按钮点击的通知方法
    @objc private func clickEmoticonButtonAction(noti: Notification) {
        let emoticon = noti.object as! HMEmoticon
        textView.insertEmoticon(emoticon: emoticon)
        
        //  保存到最近表情数组中
        HMEmoticonTools.sharedTools.saveRecentEmoticon(emoticon: emoticon) { 
            //  重新加载最近表情数据
            self.emoticonKeyBoard.reloadRecentData()
        }        
    
    }
    
    //  MARK:   --监听键盘frame的改变
    @objc private func keyBoardFrameChange(noti: Notification) {
        //  获取键盘的frame
        let keyBoardFrame = noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        print(keyBoardFrame)
        //  更新约束
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
        }
        
        //  执行约束动画
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
    //  MARK:   --点击取消按钮的事件
    @objc private func cancelAction() {
        //  失去第一响应者
        textView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    
    deinit {
        //  移除通知
        NotificationCenter.default.removeObserver(self)
    }
}

//  MARK:   --处理toolbar按钮点击事件
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //  设置键盘顶部功能条
    //        textView.inputAccessoryView
    //  表情按钮点击处理
    func emoticonButtonAction() {
        if textView.inputView == nil {
            //  设置txtView的输入视图, 由系统键盘设置成为表情键盘
            textView.inputView = emoticonKeyBoard
            //  表情键盘
            toolBar.switchButtonIcon(isEmoticonKeyBoard: true)
        } else {
            //  设置txtView的输入视图, 由表情键盘设置成为系统键盘
            textView.inputView = nil
            //  表情键盘
            toolBar.switchButtonIcon(isEmoticonKeyBoard: false)
        }
        
        //  成为第一响应者
        textView.becomeFirstResponder()
        //  重新加载自定义输入视图
        textView.reloadInputViews()
     
    }
    
    //  图片按钮点击处理
    func pictureButtonAction() {
        let imagePickCtr = UIImagePickerController()
        //  设置代理
        imagePickCtr.delegate = self
        //  判断来源类型
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //  真机
            imagePickCtr.sourceType = .camera
        } else {
            //  模拟器 设置图库
            imagePickCtr.sourceType = .photoLibrary
        }
        
        //  允许编辑
//        imagePickCtr.allowsEditing = true
        
        self.present(imagePickCtr, animated: true, completion: nil)
    }
    
    //  MARK:   --UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //  获取原始图片UIImagePickerControllerOriginalImage， 获取编辑图片的key: UIImagePickerControllerEditedImage
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        print(image)
        
        //  获取压缩后的图片
        let currentImage = scaleImage(scaleWidth: 200, image: image)
        //  给配图显示选择的图片
        pictureView.showImage(image: currentImage)
        
        //  1. 手写dismis操作
        picker.dismiss(animated: true, completion: nil)
    }
    
    /// 等比压缩图片
    ///
    /// - Parameters:
    ///   - scaleWidth: 压缩后的宽度
    ///   - image: 需要压缩的图片
    /// - Returns: 压缩后的图片
    private func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        //  压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        //  压缩后的大小
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        
        //  开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        //  把图片压缩到指定区域内
        let range = CGRect(origin: CGPoint.zero, size: scaleSize)
        image.draw(in: range)
        //  在图片上下文中获取压缩后的图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //  结束图片上下文
        UIGraphicsEndImageContext()
        
        return currentImage!
    }
}

//  MARK:   --UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //  设置按钮是否可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //  让textView失去第一响应者
        //  结束编辑就是失去第一响应者
        self.view.endEditing(true)
    }
}
